﻿using AForge.Video.DirectShow;
using AForge.Video;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Drawing;

namespace 摄像头不展示界面拍照
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();


            // 创建过滤器信息集合实例，存储连接的所有视频捕捉设备
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            // 假设使用第一个设备
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);

            // 获取可用的视频分辨率
            VideoCapabilities[] videoCapabilities = videoSource.VideoCapabilities;
            var r = videoCapabilities.OrderByDescending(x => x.FrameSize.Width).First();

            // 设置所需的分辨率
            videoSource.VideoResolution = r; // 可以根据需要选择其他分辨率

            // 初始化视频源
            videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);

            // 开始捕捉视频
            videoSource.Start();

        }

        private async void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // 获取当前帧
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();

            // 在此处进行图像处理或保存
            string filePath = $"{Guid.NewGuid()}.jpg";

            await Task.Delay(5000);
            bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Environment.Exit(0);
        }
    }
}
